package com.pwser.controller;

import com.pwser.pojo.JDGood;
import com.pwser.service.ElasticSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
public class ElasticSearchController {

    @Autowired
    private ElasticSearchService elasticSearchService;

    /**
     * 默认首页查询全部
     * @param page
     * @return
     */
    @GetMapping("/searchAll/{page}")
    public List<JDGood> searchAll(@PathVariable("page") int page) {
        List<JDGood> jdGoodList = null;
        try {
            jdGoodList = elasticSearchService.searchAll(page);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jdGoodList;
    }

    /**
     * 根据关键字查询数据
     * @param keyword
     * @param page
     * @return
     */
    @GetMapping("/search/{keyword}/{page}")
    public List<JDGood> searchByKeyword(@PathVariable("keyword") String keyword,
                                        @PathVariable("page") int page) {
        List<JDGood> jdGoodList = null;
        try {
            jdGoodList = elasticSearchService.searchByKeyword(keyword, page);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jdGoodList;
    }

    /**
     * 爬虫京东数据并索引到ES
     * @param keyword
     * @return
     */
    @GetMapping("/parse/{keyword}")
    public String parseJD(@PathVariable("keyword") String keyword) {
        boolean bulkSuccess = false;
        try {
            bulkSuccess = elasticSearchService.parseJD(keyword);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (bulkSuccess) {
            return "关键字（" + keyword + "）数据爬取成功！";
        }else {
            return "关键字（" + keyword + "）数据爬取失败！";
        }
    }
}
